import React, { Component } from 'react';
import { connect } from 'react-redux'
import { getList } from '../../../api';
class Index extends Component {
  componentDidMount() {
    this.props.getList()
  }
  // 跳转详情页
  toDetail(v) {
    this.props.history.push({ 
      pathname: '/detail', 
      state: v,
    })
  }
  render() {
    const { list } = this.props
    return (
      <div>
        {
          list.length > 0 && list.map((v, i) => {
            return (
              <dl key={i} 
              style={{
                display: 'flex'
              }}
              onClick={ () => this.toDetail(v)}
              >
                <dt><img src={v.url} alt="" /></dt>
                <dd>
                  <h3>{v.title}</h3>
                  <p>{v.desc}</p>
                </dd>
              </dl>
            )
          })
        }
      </div>
    );
  }
}

const mapStateToProps = state => {
  const { list } = state
  return {
    list,
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    // 获取列表方法
    async getList() {
      // 请求数据
      const resp = await getList();
      // 分发 action
      dispatch({ type: 'SET_LIST', payload: resp.data.data })
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Index);
